package com.seven.webhook.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.seven.webhook.service.IMailService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;


@Log4j2
@RestController
@RequestMapping("/")
public class AlertController {
    @Autowired
    IMailService iMailService;


    @RequestMapping(value = "/demo", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String pstn(@RequestBody String json) {
        log.debug("alert notify  params: {}", json);
        Map<String, Object> result = new HashMap<>();
        result.put("msg", "报警失败");
        result.put("code", 0);

        if (StrUtil.isBlank(json)) {
            return JSONUtil.toJsonStr(result);
        }
        JSONObject jo = JSONUtil.parseObj(json);

        JSONObject commonAnnotations = jo.getJSONObject("commonAnnotations");
        String status = jo.getStr("status");
        if (commonAnnotations == null) {
            return JSONUtil.toJsonStr(result);
        }


        String subject = commonAnnotations.getStr("summary");
        String content = commonAnnotations.getStr("description");
        List<String> emailusers = new ArrayList<>();
        emailusers.add("xxx@aliyun.com");

/*        List<String> users = new ArrayList<>();
        users.add("158*****5043");*/


        try {
            boolean success = iMailService.sendHtmlMail("yijialuo@gridsum.com", subject, content);
            if (success) {
                result.put("msg", "报警成功");
                result.put("code", 1);
            }
        } catch (Exception e) {
            log.error("=alert email notify error. json={}", json, e);
        }
        try {
            /*
            boolean success = Util.sms(subject, content, users);
            if (success) {
                result.put("msg", "报警成功");
                result.put("code", 1);
            }*/
        } catch (Exception e) {
            log.error("=alert sms notify error. json={}", json, e);
        }

        return JSONUtil.toJsonStr(result);
    }

}

